// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-11-19

package term_plugin

import (
	"fmt"
	"gitee.com/go-libs/log/common"
	"io"
	"os"
)

// 输出日志.
type writer struct{}

// +------------------------------------------------------------------------------+
// | Interface methods                                                            |
// +------------------------------------------------------------------------------+

func (o *writer) Write(formatter common.LoggingFormatter, items []common.Item) (err error) {
	var (
		device  io.Writer
		message string
	)

	// 遍历日志.
	for _, item := range items {
		// 日志内容.
		message = formatter.ToString(item)

		// 输出位置.
		if item.Level().IsError() || item.Level().IsFatal() {
			device = os.Stderr
		} else {
			device = os.Stdout
		}

		// 输出日志.
		if _, err = fmt.Fprintf(device, fmt.Sprintf("%s\n", message)); err != nil {
			break
		}
	}
	return
}

// +------------------------------------------------------------------------------+
// | Access methods                                                               |
// +------------------------------------------------------------------------------+

func (o *writer) init() *writer { return o }
